# -*-coding: Utf-8 -*-
# @File : app .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/10/8
from fastapi import FastAPI, status, Depends, Request
import uvicorn
from pydantic import BaseModel
# 必须模块
from fastapi.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from FastapiTest.settings.config import settings

from linux_info.main_linux_spider import RemoteServerMonitor

application = FastAPI(
    debug=True,
    title="服务器信息接口测试",
    description="根据相应操作监控服务器",
    version="0.1.0",
)

# 静态资源目录
application.mount('/static', StaticFiles(directory=settings.STATIC_DIR), name="static")
# 前端模版目录
application.template = Jinja2Templates(directory=settings.TEMPLATE_DIR)


@application.get('/test')
async def index(request: Request):
    print(request.app.state)
    return request.app.template.TemplateResponse("index.html", {"request": request})
    # return CommonResponse()


def CommonResponse(status_code=status.HTTP_200_OK, code=200, mgs="请求成功!", **kwargs):
    data = {'code': code, 'mgs': mgs}
    if kwargs:
        data.update(kwargs)
    '''
    content: typing.Any = None,
    status_code: int = 200,
    headers: dict = None,
    media_type: str = None,
    background: BackgroundTask = None,
    '''
    return data


# 创建子依赖对象
def get_db():
    # 初始化 链接对象
    monitor = RemoteServerMonitor()
    try:
        yield monitor
    finally:
        monitor.close()


'''
 # 获取CPU使用率 :
    cpu_usage = str(monitor.get_cpu_usage()) + '%'
    # 获取CPU详细信息 ： {'cpu_model': 'Intel(R) Xeon(R) Platinum 8255C CPU @ 2.50GHz', 'cpu_core_total': '2', 'cpu_physics_per': '1\n', 'user_cpu_use': '0.0', 'sys_cpu_use': '3.1'}
    cpu_info = monitor.get_cpu_info()


    memory_usage = monitor.get_memory_usage_formatted()
    network = monitor.get_network_interfaces_formatted()
    who_ip_address = monitor.get_who_formatted()
    netstat = monitor.get_netstat_formatted()

    # 指定单条命令 ：输入指令
    monitor.execute_command("docker ps")
    server_data = {
    }
    monitor.close()
    print(server_data)

'''


@application.get('/sys')
async def update_info(request: Request, monitor: RemoteServerMonitor = Depends(get_db)):
    # 获取服务器详细信息：
    # {'hostname': 'VM-8-11-opencloudos',
    # 'release_info': '',
    # 'kernel_version': '5.4.119-20.0009.21.spr',
    # 'system_type': 'x86_64',
    # 'boot_time': '2023-10-08 13:00',
    # 'uptime': '5:32'}
    sys_info = monitor.get_system_info()
    # 获取CPU使用率 :
    cpu_usage = str(monitor.get_cpu_usage()) + '%'
    # 获取CPU详细信息 ： {
    # 'cpu_model': 'Intel(R) Xeon(R) Platinum 8255C CPU @ 2.50GHz',
    # 'cpu_core_total': '2',
    # 'cpu_physics_per': '1\n',
    # 'user_cpu_use': '0.0',
    # 'sys_cpu_use': '3.1'}
    cpu_info = monitor.get_cpu_info()

    # 获取负载值 ： {'first': '0.08', 'second': '0.11', 'third': '0.13'}
    load_average = monitor.get_load_average()

    # 获取详细磁盘使用率
    # disk_usage = [entry for entry in monitor.get_disk_usage()]
    # 获取磁盘使用率
    # {
    #             'filesystem_size': filesystem_size,
    #             'used_space': used_space,
    #             'available_space': available_space,
    #             'usage_percent': usage_percent,
    #             'mount_point': mount_point,
    #         }
    disk_usage = monitor.get_disk_usage()
    # 获取更加详细的inode 信息 ： {
    # 'filesystem': '/dev/vda1',
    # 'inodes': '3276800',
    # 'iUsed': '874525',
    # 'iFree': '2402275',
    # 'iUse': '27%',
    # 'mount_point': '/'}
    inode_data = monitor.get_inode_info()
    # 获取docker容器中的所有值 [{一个容器},{一个容器}]
    docker_container = monitor.get_docker_data()
    return request.app.template.TemplateResponse("home.html",
                                                 {"request": request,
                                                  'sys_info': sys_info,
                                                  'cpu_usage': cpu_usage,
                                                  'cpu_info': cpu_info,
                                                  'load_average': load_average,
                                                  'disk_usage': disk_usage,
                                                  'inode_data': inode_data,
                                                  'docker_container': docker_container,
                                                  })


@application.get('/get_ip_address')
async def get_ip_address():
    return CommonResponse(ip_address=1)


@application.get('/docker')
async def get_docker(monitor: RemoteServerMonitor = Depends(get_db)):
    # 获取docker容器中的所有值 [{一个容器},{一个容器}]
    docker_container = monitor.get_docker_data()
    return CommonResponse(docker_container=docker_container)


class ExecuteCommand(BaseModel):
    username: str
    command: str


@application.post('/execute_command')
async def execute_command(command: ExecuteCommand, monitor: RemoteServerMonitor = Depends(get_db)):
    cmd = command.dict().get('command')
    output = monitor.execute_command(cmd.strip())
    return CommonResponse(result=output.strip())


@application.get('/shell')
async def shell(request: Request, monitor: RemoteServerMonitor = Depends(get_db)):
    return request.app.template.TemplateResponse("web_socket_shell.html", {'request': request})


def run():
    uvicorn.run('app:application', host='127.0.0.1', port=8585, reload=True, workers=1)


if __name__ == '__main__':
    run()
